//
//  LoginViewController.m
//  QinRen
//
//  Created by Donny on 15/2/27.
//  Copyright (c) 2015年 Donny. All rights reserved.
//

#import "LoginViewController.h"
#import "AppDelegate.h"
#import "User.h"

#import "ForgetSecViewcomtroller.h"
#import "UIImageView+EMWebCache.h"
/*
 {"verification":true,"total":1,"data":[{"uid":"1","username":"15818738100","realname":"15818738100","icon":"","funds":"2797669.60","Integral":"958073.00","mshopid":"0","paypwd":"49ba59abbe56e057","groupid":"1","groupname":"普通会员组","discount":"100.00","msg":"登录成功","status":"1"}],"error":null}
 */
 

@interface LoginViewController ()<UITextFieldDelegate>

@property (strong, nonatomic)  UIView *iconView;
@property (strong, nonatomic)  UIImageView *iconImageView;

@property (strong, nonatomic) IBOutlet UIView   *passwordBackGroundView;
@property (strong, nonatomic) IBOutlet UIButton *signUpButton;
@property (strong, nonatomic) IBOutlet UIButton *loginButton;
@property (strong, nonatomic) IBOutlet UIButton *savePwButton;
@property (strong, nonatomic) IBOutlet UIButton *saveUserButton;


@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"登录";
   // User *user = [User sharedUser];
//    NSString *passwd = user.paypwd;
//    NSString *userid = user.uid;
   
    // Do any additional setup after loading the view from its nib.
    self.signUpButton.layer.cornerRadius = 6.0f;

    self.loginButton.layer.cornerRadius = 6.0f;
    
    
    self.iconView = [[UIView alloc]initWithFrame:CGRectMake((SCREEN_W-100)/2,40, 100, 100)];
    self.iconImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
//    [self.iconImageView setImage:[UIImage imageNamed:@"blue_logo"]];
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:UserImage]] placeholderImage:[UIImage imageNamed:@"redLogo"]];
    
    self.iconImageView.layer.cornerRadius = 50;
    self.iconImageView.layer.masksToBounds = YES;
    [self.iconView addSubview:self.iconImageView];
    [self.view addSubview:self.iconView];
    
    
    self.userField.keyboardType = UIKeyboardTypeDefault;
    self.pwField.keyboardType = UIKeyboardTypeDefault;
    
    if ([[NSUserDefaults standardUserDefaults]boolForKey:ifSaveAccount])
    {
        self.userField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"username"];
        self.saveUserButton.selected = YES;
        if ([[NSUserDefaults standardUserDefaults]boolForKey:ifSavePassword]) {
            self.pwField.text = [[NSUserDefaults standardUserDefaults]objectForKey:@"password"];
            self.savePwButton.selected = YES;
        }
        
        [self requestForLogin];
        
    }
    
    //self.userField.text = @"yangshan";
    //self.pwField.text = @"123";
    
    /**
     *  响应式编程
     *
     */
    
//    RAC(self.loginButton,hidden) = [RACSignal
//                                    combineLatest:@[
//                                                    self.pwField.rac_textSignal,
//                                                    self.userField.rac_textSignal,
//                                                    ]
//                                    reduce:^id(NSString *username,NSString *passwd){
//                                        return @(username.length == 0 || passwd.length == 0);
//                                        
//                                    }];
//    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.view addGestureRecognizer:tapGestureRecognizer];
//
//    if(SCREEN_H <= 600)
//    {
//    
//        //使用通知中心来获取键盘的弹出
//        //1.打开收音机 -- 获取NSNotificationCenter实例
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        
//        //2.调整频率，收听想要听的节目  -- 监听指定广播
//        //3.接收到通知之后要做的事情
//        [center addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//        [center addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//    
//    }
    
    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [UIView animateWithDuration:0.25 animations:^{
    self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
    //[textField resignFirstResponder];
    [_userField resignFirstResponder];
    [_pwField resignFirstResponder];
    return YES;
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap{
    [_userField resignFirstResponder];
    [_pwField resignFirstResponder];

    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = CGRectMake(0, 64, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
}

- (void)keyBoardWillHide:(NSNotification *)info
{
    [UIView animateWithDuration:0.25 animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame));
    }];
}
//
//- (void)keyBoardWillShow:(NSNotification *)info
//{
//    NSLog(@"info = %@", info);
//    
//    //获取当前触发键盘的文本框对象
//    //UITextField *textField = info.object;
//    
//    //获取键盘信息
//    NSDictionary *keyBoardInfo = info.userInfo;
//    
//    //获取
//    NSValue *rectValue = keyBoardInfo[UIKeyboardFrameEndUserInfoKey];
//    //将NSValue --> CGRect
//    //1.准备一个空的CGRect变量
//    CGRect keyBoardFrame;
//    
//    //2.将该变量交给NSValue对象
//    [rectValue getValue:&keyBoardFrame];
//    
//
//        
//    //修改当前view的y坐标
//    NSInteger offset = self.view.frame.size.height - keyBoardFrame.origin.y - 150;
//    
//    CGRect viewFrame = self.view.frame;
//    viewFrame.origin.y = -offset;
//    
//    [UIView animateWithDuration:0.25 animations:^{
//        self.view.frame = viewFrame;
//    }];
//
//
//
//    
//    NSLog(@"keyBoardFrame = %@", NSStringFromCGRect(keyBoardFrame));
//    
//}
//
#define zhengn

- (IBAction)gotoSignUp:(id)sender
{
    //[self performSegueWithIdentifier:@"SignUp" sender:self];

}


- (void)requestForLogin
{
    if (self.userField.text.length <= 0 || self.pwField.text.length <= 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请填写用户名或密码"];
        return;
    }
    
    
    [SVProgressHUD show];
    
    EAHttpAPIClient *manager = [EAHttpAPIClient manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSDictionary *parameters = @{@"username":self.userField.text,@"password":self.pwField.text};
    
    [manager GetWithParameters:parameters method:@"get.manager.info" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *resposeString ;
        if ([responseObject isKindOfClass:[NSData class]]) {
            resposeString = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        }else
            resposeString = responseObject;
        
        NSString *jsonString = [DataParser parseString:resposeString];
        id dictionary = [JSONKit jsonToArrayOrDictionary:jsonString];
        NSLog(@"dictonary :%@",[dictionary description]);
        
        
        if ([[dictionary objectForKey:@"verification"]intValue] >= 1)
        {
            if ([dictionary[@"data"] isKindOfClass:[NSArray class]])
            {
                
                NSDictionary *useDictionary = [[dictionary objectForKey:@"data"]firstObject];
                if ([[useDictionary objectForKey:@"status"]intValue] <= 0)
                {
                    [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
                    
                }else
                {
                    //
                    [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                    [NSThread sleepForTimeInterval:1.0f];
                    
                    //
                    if (self.saveUserButton.selected)
                    {
                        [[NSUserDefaults standardUserDefaults]setObject:self.userField.text  forKey:@"username"];
                        if (self.savePwButton.selected)
                        {
                            [[NSUserDefaults standardUserDefaults]setObject:self.pwField.text forKey:@"password"];
                        }
                    }
                    
                    //
                    User *user = [User sharedUser];
                    
                    [user setUserInfo:useDictionary];
                    
                    [[NSUserDefaults standardUserDefaults]setObject:user.employee_img forKey:UserImage];
                    
                    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    
                    [appdelegate setupTabbar];
                    
                    //环信登陆
                    [[EaseMob sharedInstance] registerSDKWithAppKey:HXAppKey apnsCertName:nil];
                    // [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:USERNAME password:PASSWORD];
                    
                    user.hx_userpwd = self.pwField.text;
                    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:user.hx_username password:user.hx_userpwd completion:^(NSDictionary *loginInfo, EMError *error) {
                        NSLog(@"loginInfo--%@",loginInfo);
                    } onQueue:nil];

                    
                    [self presentViewController:appdelegate.tabbarController animated:YES completion:NULL];
                    
                }
            }
            
            
        }else
        {
            NSString *error = [dictionary objectForKey:@"error"];
            [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
            [SVProgressHUD showErrorWithStatus:error];
            
            
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showWithMaskType:SVProgressHUDMaskTypeClear];
        [SVProgressHUD showErrorWithStatus:[error localizedDescription]];

    }];
    

}

//-(void) setInputTextFieldForNull {
//    
//    [[NSUserDefaults standardUserDefaults]setObject:@""  forKey:@"username"];
//    [[NSUserDefaults standardUserDefaults]setObject:@""  forKey:@"username"];
//
//    self.savePwButton.selected = NO;
//    self.savePwButton.selected = NO;
//}

- (IBAction)login:(id)sender
{
    [self requestForLogin];
}

- (IBAction)savepassword:(id)sender
{
    self.savePwButton.selected = !self.savePwButton.selected;
    [[NSUserDefaults standardUserDefaults]setBool:self.savePwButton.selected forKey:ifSavePassword];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

- (IBAction)saveaccount:(id)sender
{
    self.saveUserButton.selected = !self.saveUserButton.selected;
    [[NSUserDefaults standardUserDefaults]setBool:self.saveUserButton.selected forKey:ifSaveAccount];
    [[NSUserDefaults standardUserDefaults]synchronize];
}



- (void)forgetpassword
{
//    ForgetSecViewcomtroller *vc=[[ForgetSecViewcomtroller alloc]init];
//    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//    if (textField == [self.view viewWithTag:10086]) {
////        [self forgetpassword];
//        return NO;
//    }
    
//    if (textField == [self.view viewWithTag:10085]) {
//        self.savePwButton.selected = !self.savePwButton.selected;
//        [[NSUserDefaults standardUserDefaults]setBool:self.savePwButton.selected forKey:ifSavePassword];
//        [[NSUserDefaults standardUserDefaults]synchronize];
//        return NO;
//    }
//    
//    if (textField == [self.view viewWithTag:10084]) {
//        self.saveUserButton.selected = !self.saveUserButton.selected;
//        [[NSUserDefaults standardUserDefaults]setBool:self.saveUserButton.selected forKey:ifSaveAccount];
//        [[NSUserDefaults standardUserDefaults]synchronize];
//        return NO;
//    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
